`
Listing 2-16
The use of continue in a for loop
We start a for loop using the example_file* glob, which will expand to
match the names of all files starting with example_file in the directory where the
script runs 1. As a result, the loop should iterate over all three files we created
earlier. Within the loop, we use a file test operator to check whether the filename is
equal to example_file1 because we want to skip this file and not make any changes
to it. If the condition is met, we use the continue statement 2 to proceed to the
next iteration, leaving the file unmodified. Later in the loop, we use the echo
command with the environment variable ${RANDOM} to generate a random
number and write it into the file.
Save this script as for_loop_continue.sh and execute it in the same directory
as the three files.
$ chmod u+x for_loop_continue.sh
$./for_loop_continue.sh
Skipping the first file.
If you examine the files, you should see that the first file is empty while the
other two contain a random number as a result of the script echoing the value of
the ${RANDOM} environment variable into them.
Case Statements
In bash, case statements allow you to test multiple conditions in a cleaner
way by using more readable syntax. Often, they help you avoid many if
conditions, which can become harder to read as they grow in size.
Listing 2-17 shows the case statement syntax.
case EXPRESSION in
PATTERN1)
# do something if the first condition is met
;;
PATTERN2)
# do something if the second condition is met
;;
esac
Listing 2-17
The case statement syntax
Case statements start with the keyword case followed by some expression,
such as a variable you want to match a pattern against. PATTERN1 and
PATTERN2 in this example represent some pattern case (such as a regular
expression, a string, or an integer) that you want to compare to the expression. To
close a case statement, you use the keyword esac (case inverted).
Let’s take a look at an example case statement that checks whether an IP
address is present in a specific private network (Listing 2-17).
#!/bin/bash
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks